package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;

public class EchoHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);
        Map<String, String> params = request.getAllParams();

        StringBuilder contentBuilder = new StringBuilder();
        contentBuilder.append("<h1>Echo Server Response</h1>");
        contentBuilder.append("<h2>Request Details:</h2>");
        contentBuilder.append("<p>Method: ").append(request.getMethod()).append("</p>");
        contentBuilder.append("<p>URL: ").append(request.getUrl()).append("</p>");
         //TODO：【222024321072046/马云山]
        // 构建参数列表
        if (params.isEmpty()) {
            contentBuilder.append("<h2>No Parameters Received.</h2>");
        } else {
            contentBuilder.append("<h2>Received Parameters:</h2>");
            contentBuilder.append("<ul>");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                contentBuilder.append("<li><strong>").append(entry.getKey())
                        .append("</strong>: ").append(entry.getValue()).append("</li>");
            }
            contentBuilder.append("</ul>");
        }

        String content = contentBuilder.toString();

        // TODO：【222024321072046/马云山] 构建HTTP响应
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/html; charset=UTF-8");
        writer.println("Content-Length: " + content.getBytes().length);
        writer.println("Connection: close");
        writer.println();

        writer.println(content);
        writer.flush();
    }
}